package com.zkzl.cdz.command;

import com.zkzl.cdz.dao.CmdStructure;
import com.zkzl.cdz.dao.Constant;
import com.zkzl.cdz.dao.PileSession;
import com.zkzl.cdz.dao.SysDao;
import com.zkzl.cdz.netty.JRedisPool;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * * @program: NettyTEST
 * * @description: 启动指令应答
 * * @author: QSY
 * * @create: 2019-07-22 11:57
 */
@Slf4j
@Component
public class Cmd_0x43 {

    @Autowired
    SysDao sysDao;

    /**
     * 这里只需要解析sessionId即可
     *
     * @param ctx
     * @param cs
     */
    public void Execute(ChannelHandlerContext ctx, CmdStructure cs) {
        //不进行tb_session表的删除工作，所以这里一定可以获取到code的值，但是sessionId可能是过期的
        log.info("启动指令应答_0x43");
        PileSession param = new PileSession();
        param.setSessionId(ctx.channel().id().toString());
        PileSession pileSession = sysDao.findPileSession(param);

        try {
            for (int i = 0; i < 5; i++) {
                if (pileSession != null) {
                    String code = pileSession.getCode().trim();
                    log.info(code + "桩回复启动结果" + cs.body[0]);
                    if (cs.body[0] == 4 || cs.body[0] == 0) {
                        JRedisPool.setKV(code + cs.gun, Constant.gunState.error, 2);
                    } else if (cs.body[0] == 2) {
                        JRedisPool.setKV(code + cs.gun, Constant.gunState.gunError, 2);
                    } else if (cs.body[0] == 3) {
                        JRedisPool.setKV(code + cs.gun, Constant.gunState.inUse, 2);
                    }
                    break;
                } else {
                    log.error("有桩回复，但是未登录！无法识别身份！");
                    Thread.sleep(2000);
                    pileSession = sysDao.findPileSession(param);
                }
            }
        } catch (Exception e) {
            log.error("启动指令应答异常", e);
        }
    }

}
